package com.isoft.illustrationsdraw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.illustrationsdraw.entity.LikeTag;
import com.isoft.illustrationsdraw.mapper.LikeTagMapper;
import com.isoft.illustrationsdraw.service.LikeTagService;
import com.isoft.illustrationsdraw.service.TagService;

import java.util.List;

import org.springframework.stereotype.Service;

@Service
public class LikeTagServiceImpl extends ServiceImpl<LikeTagMapper, LikeTag> implements LikeTagService {
    
    private final TagService tagService;

    public LikeTagServiceImpl(TagService tagService) {
        this.tagService = tagService;
    }
    
    @Override
    public List<LikeTag> getLikeTagsByUser(Long userId) {
        var lambdaQueryWrapper = new LambdaQueryWrapper<LikeTag>();
        lambdaQueryWrapper.eq(LikeTag::getUserId, userId);
        return list(lambdaQueryWrapper);
    }

    @Override
    public LikeTag getUserLikeTag(Long userId, String tagName, Long tagId) {
        // 参数校验
        if ((tagName == null && tagId == null) || userId == null) {
            return null;
        }
    
        QueryWrapper<LikeTag> wrapper = new QueryWrapper<>();
    
        // 如果 tagId 为空但 tagName 不为空，通过 tagName 查询 tagId
        if (tagId == null && tagName != null) {
            tagId = tagService.getTagIdByName(tagName);
            if (tagId == null) {
                // 如果 tagName 找不到对应的 tagId，直接返回 false
                return null;
            }
        }
    
        // 构建查询条件
        wrapper.eq("user_id", userId)
               .eq("tag_id", tagId);
    
        // 判断是否存在匹配记录
        return getOne(wrapper);
    }
    
}
